<template>
  <BasicModal
    :title="t('layout.header.dropdownItemChangeProject')"
    v-bind="$attrs"
    @register="registerModal"
    @ok="onButtonOkClick"
    @cancel="onButtonCancelClick"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, computed, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { UserModifyPasswordDto } from '/@/api/platform/model/userModel';
  import { modifyPassword } from '/@/api/platform/uac';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal/index';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useUserStore } from '/@/store/modules/user';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { qcLoginPasswordEncrypt } from '/@/utils/cipher';
  import { useAppStoreWithOut } from '/@/store/modules/app';
  import { useMultipleTabStore } from '/@/store/modules/multipleTab';

  export default defineComponent({
    name: 'ChangeProjectModal',
    components: { BasicModal, BasicForm },

    setup() {
      const { t } = useI18n();
      const router = useRouter();
      const { createErrorModal, notification } = useMessage();
      const permissionStore = usePermissionStore();
      const userStore = useUserStore();

      const [registerModal, { setModalProps, closeModal }] = useModalInner(() => {
        console.log(userStore.getUserValidProjects, 'getUserValidProjects');
      });

      const [registerForm, { validate, resetFields, updateSchema }] = useForm({
        labelWidth: 80,
        showActionButtonGroup: false,
        schemas: [
          {
            field: 'project',
            label: '项目',
            component: 'Select',
            required: true,
            componentProps: () => {
              return {
                options: userStore.getUserValidProjects.map((item) => {
                  return {
                    label: item.objname,
                    value: item.objcode,
                  };
                }),
              };
            },
            defaultValue: userStore.getUserCurrentProjectCode,
            colProps: { span: 23 },
          },
        ],
      });

      /*
       * 点击切换项目确定按钮
       */
      async function onButtonOkClick() {
        const values = await validate();
        //获取当前项目编码和要切换的目标项目编码
        let currToken = userStore.getToken;
        let currProjectCode = userStore.getUserCurrentProjectCode;
        let destProjectCode = values.project;
        console.log(
          '切换项目确定按钮点击，currToken=' +
            currToken +
            '，currProjectCode=' +
            currProjectCode +
            '，destProjectCode=' +
            destProjectCode,
        );
        /*
         * 切换项目需要重新赋值和保留的数据处理逻辑如下：
         * 2025-5-15，实测不需要对任何数据进行重置赋值和保留（token必须保留现有的，如果跨域名进行切换需要在url中显式传递）；针对项目的菜单和路由会在跳转后进入Layout时重新根据token进行用户信息和权限菜单的获取
         */
        // userStore.setUserCurrentProject(
        //   userStore.getUserValidProjects.find((item) => item.objcode == values.project),
        // );
        // userStore.setUserCurrentProjectCode(values.project);
        // 重新获取route构建路由, 清空当前项目缓存的路由, 最后跳转
        // permissionStore.setDynamicAddedRoute(false);
        // useAppStoreWithOut().clearMenuRoute();
        // const tabStore = useMultipleTabStore();
        // tabStore.resetState();
        onButtonCancelClick();
        // await userStore.afterLoginAction();
        //设置当前窗口的href进行跳转，跳转的url前面保持相同，中间的项目编码进行替换，最后的跳转路由固定为默认首页/home/index
        //可以修改为现有的url中匹配以斜线包裹的项目编码进行替换，如将/cms/替换为/qms/
        // let route =
        //   window.location.href.split(`/${currProjectCode}/`)[0] + `/${destProjectCode}/#/login`;
        let route =
          window.location.href.split(`/${currProjectCode}/`)[0] +
          `/${destProjectCode}/#/home/index`;
        console.log(
          '切换项目确定按钮点击，currProjectCode=' +
            currProjectCode +
            '，destProjectCode=' +
            destProjectCode +
            '跳转route=' +
            route,
        );
        setTimeout(() => {
          window.location.href = route;
        }, 0);
      }

      function onButtonCancelClick() {
        resetFields();
        closeModal();
      }

      onMounted(() => {
        console.log(userStore.getUserValidProjects, 'getUserValidProjects');
        console.log(userStore.getUserCurrentProject, 'getUserCurrentProject');
      });

      return {
        t,
        registerModal,
        registerForm,
        onButtonOkClick,
        onButtonCancelClick,
      };
    },
  });
</script>
<style lang="less"></style>
